package com.xwj.nio.file;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * nio通道channel之FileChannel
 *
 * @author xwj
 * @date 2020/6/10
 */
public class NioFileChannelDemo {
    public static void main(String[] args) {
        nioCopyFile("C:\\Users\\Administrator\\Desktop\\elasticsearch.yml", "C:\\Users\\Administrator\\Desktop\\elasticsearch1.yml");
    }

    /**
     * 基于缓冲区+channel的文件拷贝
     * @param src
     * @param dest
     */
    public static void nioCopyFile(String src, String dest) {
        File srcFile = new File(src);
        File destFile = new File(dest);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            int len = -1;
            ByteBuffer buf = ByteBuffer.allocate(1024);
            // 从输入通道读取到buffer
            while((len = inChannel.read(buf)) != -1) {
                // 变成读模式
                buf.flip();
                int outLen = 0;
                while((outLen = outChannel.write(buf)) != 0) {
                }
                // 变成写模式
                buf.clear();
            }
            outChannel.force(true);
        } catch (Exception e) {
        } finally {
            try {
                if(outChannel != null) {
                    outChannel.close();
                }
                if(fos != null) {
                    fos.close();
                }
                if(inChannel != null) {
                    inChannel.close();
                }
                if(fis != null) {
                    fis.close();
                }
            } catch (Exception e) {}
        }

    }
}
